package com.yulang.security.core.config;

import com.yulang.security.core.filter.ImageCodeValidateFilter;
import com.yulang.security.core.filter.MobileValidateFilter;
import com.yulang.security.core.handler.CustomLogoutHandler;
import com.yulang.security.core.properties.SecurityProperties;
import com.yulang.security.core.provider.AuthorizeConfigureManager;
import com.yulang.security.core.provider.AuthorizeConfigureProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.sql.DataSource;

/**
 * spring-security核心配置类
 * 1.开启webSecurity @EnableWebSecurity
 * 2.覆盖父类的方法
 */
@Slf4j
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;


    @Qualifier("customUserService")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthenticationSuccessHandler successHandler;

    @Autowired
    private MobileValidateFilter mobileValidateFilter;

    @Autowired
    private AuthenticationFailureHandler failureHandler;

    @Autowired
    private ImageCodeValidateFilter imageCodeValidateFilter;

    @Autowired
    private InvalidSessionStrategy invalidSessionStrategy;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private MobileAuthenticationConfig mobileAuthenticationConfig;

    @Autowired
    private SessionInformationExpiredStrategy expiredSessionStrategy;

    @Autowired
    private CustomLogoutHandler customLogoutHandler;

    @Autowired
    private SessionRegistry sessionRegistry;

    @Autowired
    private AuthorizeConfigureManager authorizeConfigureProvider;

    @Bean
    public JdbcTokenRepositoryImpl jdbcTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    };


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 认证管理器
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
                .withUser("admin")
                .password(passwordEncoder().encode("123"))
                .authorities("ADMIN");
        */
        auth.userDetailsService(userDetailsService);
    }

    /**
     * 针对http请求做认证
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*http.httpBasic()//开启basic认证
                .and()
                .authorizeRequests() //认证请求
                .anyRequest().authenticated();//所有请求都要经过认证*/
        http.csrf().disable();
        http.addFilterBefore(mobileValidateFilter,UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class).formLogin() //表单认证方式
                .loginPage(securityProperties.getAuthentication().getLoginPage())
                .loginProcessingUrl(securityProperties.getAuthentication().getLoginProcessingUrl())
                .successHandler(successHandler)
                .failureHandler(failureHandler)
                .and()
                .rememberMe()
                .tokenRepository(jdbcTokenRepository())
                .tokenValiditySeconds(securityProperties.getAuthentication()
                        .getTokenValiditySeconds())
                .and().sessionManagement()
                .invalidSessionStrategy(invalidSessionStrategy)
                .maximumSessions(1) //每个用户最多有几个session
                .expiredSessionStrategy(expiredSessionStrategy)
                // .maxSessionsPreventsLogin(true)//当一个用户达到最大的session数，则不允许后面再登录
                .sessionRegistry(sessionRegistry)
                .and()
                .and()
                .logout()
                .addLogoutHandler(customLogoutHandler)
                .logoutUrl("/user/logout") //自定义退出的url
                .logoutSuccessUrl("/login")
                .deleteCookies("JESSIONID")//退出成功时删除的cookie值
        ;
        //将手机认证添加到过滤器链上
        http.apply(mobileAuthenticationConfig);
        //將授權統一的管理起來
        authorizeConfigureProvider.configure(http.authorizeRequests());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(securityProperties.getAuthentication().getStaticPaths());
    }


}
